package com.example.grpcserver.config;

import io.grpc.ServerInterceptor;
import net.devh.boot.grpc.server.interceptor.GrpcGlobalServerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;

/**
 * gRPC 服务器配置类
 */
@Configuration
public class GrpcServerConfig {

    /**
     * 全局服务器拦截器，用于记录请求日志
     */
    @GrpcGlobalServerInterceptor
    public ServerInterceptor logServerInterceptor() {
        return new LogGrpcInterceptor();
    }

    /**
     * 日志拦截器
     */
    private static class LogGrpcInterceptor implements ServerInterceptor {
        private static final Logger log = LoggerFactory.getLogger(LogGrpcInterceptor.class);

        @Override
        public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
                ServerCall<ReqT, RespT> serverCall,
                Metadata metadata,
                ServerCallHandler<ReqT, RespT> serverCallHandler) {
            
            log.info("收到 gRPC 调用: {} - 元数据: {}", 
                    serverCall.getMethodDescriptor().getFullMethodName(), 
                    metadata);
            
            return serverCallHandler.startCall(new ForwardingServerCall<ReqT, RespT>(serverCall) {
                @Override
                public void sendHeaders(Metadata headers) {
                    log.info("发送响应头: {}", headers);
                    super.sendHeaders(headers);
                }

                @Override
                public void sendMessage(RespT message) {
                    log.info("发送响应消息: {}", message);
                    super.sendMessage(message);
                }
            }, metadata);
        }
        
        private static class ForwardingServerCall<ReqT, RespT> extends ServerCall<ReqT, RespT> {
            private final ServerCall<ReqT, RespT> delegate;

            ForwardingServerCall(ServerCall<ReqT, RespT> delegate) {
                this.delegate = delegate;
            }

            @Override
            public void request(int numMessages) {
                delegate.request(numMessages);
            }

            @Override
            public void sendHeaders(Metadata headers) {
                delegate.sendHeaders(headers);
            }

            @Override
            public void sendMessage(RespT message) {
                delegate.sendMessage(message);
            }

            @Override
            public void close(io.grpc.Status status, Metadata trailers) {
                delegate.close(status, trailers);
            }

            @Override
            public boolean isCancelled() {
                return delegate.isCancelled();
            }

            @Override
            public io.grpc.MethodDescriptor<ReqT, RespT> getMethodDescriptor() {
                return delegate.getMethodDescriptor();
            }
        }
    }
} 